package com.tools.ringtone.edit;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.mp3.dwonloader.ringtonemaker.musicradio.zl.R;



/**
 * After a ringtone has been saved, this activity lets you pick a contact and
 * assign the ringtone to that contact.
 */
public class ContactSelectActivity extends ListActivity implements TextWatcher {
	private TextView mFilter;
	private SimpleCursorAdapter mAdapter;
	private Uri mRingtoneUri;

	private TextView mTitle;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		final Intent intent = getIntent();
		mRingtoneUri = intent.getData();
		setTitle("Contact Select");
		// Inflate our UI from its XML layout description.
		setContentView(R.layout.choose_contact);

		setupViews();

		try {
			mAdapter = new SimpleCursorAdapter(this,
			// Use a template that displays a text view
					R.layout.list_item_contact,
					// Give the cursor to the list adatper
					createCursor(""),
					// Map from database columns...
					new String[] { People.CUSTOM_RINGTONE, People.STARRED,
							People.DISPLAY_NAME },
					// To widget ids in the row layout...
					new int[] { R.id.row_ringtone, R.id.row_starred,
							R.id.row_display_name });

			mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
				@Override
				public boolean setViewValue(View view, Cursor cursor,
						int columnIndex) {
					final String name = cursor.getColumnName(columnIndex);
					final String value = cursor.getString(columnIndex);
					if (name.equals(People.CUSTOM_RINGTONE)) {
						if (value != null && value.length() > 0) {
							view.setVisibility(View.VISIBLE);
						} else {
							view.setVisibility(View.INVISIBLE);
						}
						return true;
					}
					if (name.equals(People.STARRED)) {
						if (value != null && value.equals("1")) {
							view.setVisibility(View.VISIBLE);
						} else {
							view.setVisibility(View.INVISIBLE);
						}
						return true;
					}

					return false;
				}
			});

			setListAdapter(mAdapter);
			getListView().setDivider(
					getResources().getDrawable(R.drawable.ic_divider_ringtone));
			getListView().setCacheColorHint(Color.TRANSPARENT);
			// On click, assign ringtone to contact
			getListView().setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					assignRingtoneToContact();
				}
			});

		} catch (final SecurityException e) {
			// No permission to retrieve contacts?
		}

		mFilter = (TextView) findViewById(R.id.edit_keyword);
		if (mFilter != null) {
			mFilter.addTextChangedListener(this);
		}
		
		
//		final LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
//		final AdView adView = new AdView(this, AdSize.BANNER, "a14e3cab66eea7a");
//		layout.addView(adView);
//		adView.loadAd(new AdRequest());
	}

	private void setupViews() {
		// mTitle = (TextView) findViewById(R.id.text_title);
		// mTitle.setText("Contact select");
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	public void afterTextChanged(Editable s) {
		final String filterStr = mFilter.getText().toString();
		mAdapter.changeCursor(createCursor(filterStr));
	}

	private boolean isEclairOrLater() {
		return Build.VERSION.SDK_INT >= 5;
	}

	private Uri getContactContentUri() {
		if (isEclairOrLater()) {
			return Uri.parse("content://com.android.contacts/contacts");
		} else {
			return Contacts.People.CONTENT_URI;
		}
	}

	private void assignRingtoneToContact() {
		final Cursor c = mAdapter.getCursor();
		int dataIndex = c.getColumnIndexOrThrow(People._ID);
		final String contactId = c.getString(dataIndex);

		dataIndex = c.getColumnIndexOrThrow(People.DISPLAY_NAME);
		final String displayName = c.getString(dataIndex);

		final Uri uri = Uri.withAppendedPath(getContactContentUri(), contactId);

		final ContentValues values = new ContentValues();
		values.put(People.CUSTOM_RINGTONE, mRingtoneUri.toString());
		getContentResolver().update(uri, values, null, null);

		final String message = getResources().getText(
				R.string.success_contact_ringtone)
				+ " " + displayName;

		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		finish();
		return;
	}

	private Cursor createCursor(String filter) {
		String selection;
		if (filter != null && filter.length() > 0) {
			selection = "(DISPLAY_NAME LIKE \"%" + filter + "%\")";
		} else {
			selection = null;
		}
		final Cursor cursor = managedQuery(getContactContentUri(), new String[] {
				People._ID, People.CUSTOM_RINGTONE, People.DISPLAY_NAME,
				People.LAST_TIME_CONTACTED, People.STARRED,
				People.TIMES_CONTACTED }, selection, null, "STARRED DESC, "
				+ "TIMES_CONTACTED DESC, " + "LAST_TIME_CONTACTED DESC, "
				+ "DISPLAY_NAME ASC");

		return cursor;
	}
}
